﻿using Jesai.DynamicDataSource.Sqlsugar.DbConn;
using Microsoft.Extensions.Configuration;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Text;
using System.Threading.Tasks;

namespace Jesai.DynamicDataSource.Sqlsugar.Abstractions
{
    internal class DefaultDBConnectionProvider : IDBConnectionProvider
    {
        private readonly IConfiguration _configuration;

        public DefaultDBConnectionProvider(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        public async Task<List<DBConnection>> GetDbConnections()
        {
            //获取appsettings.json中配置的数据库连接字符串
            var optionSection = _configuration.GetSection("DynamicSource");
            var connectionSection = optionSection.GetSection("Connections");
            if (connectionSection != null)
            {
                //connectionSection是一个集合，里面有链接对象Connection.Connection有多个属性，如ConnectionString、ProviderName、DataType等
                List<DBConnection> connections = new List<DBConnection>();
                foreach (var connection in connectionSection.GetChildren())
                {
                    DBConnection dBConnection = new DBConnection();

                    //根据配置的连接字符串创建DbConnection对象
                    dBConnection.Name = connection.GetValue<string>("Name");
                    dBConnection.ConnectionString = connection.GetValue<string>("ConnectionString");
                    //如何把字符串的DbType 转为 DbType类型？
                    dBConnection.DbType = (DbType)Enum.Parse(typeof(DbType), connection.GetValue<string>("DbType"));
                    dBConnection.IsAutoCloseConnection = connection.GetValue<bool>("IsAutoCloseConnection");
                    connections.Add(dBConnection);
                }
                return connections;
            }

            return null;
        }
    }
}
